const api = 'http://api.zymk.cn/app_api/v3/'
const comic_id = location.pathname.split('/')[2]
const userInfo = getCookie('user')
const { type, openid } = userInfo

var subsList = getStore('subsList') || [];
var readList = getStore('readList') || [];
var isCollect = subsList.some(item => {
	return item.comic_id == comic_id;
})
if(isCollect) $('.like').removeClass('ift-collect').addClass('ift-lovered')

	var orderBy = false;
var score = 0;

var layer = {
	msg: function(text) {
		var _this = this;
		_this.reset();
		var html;
		$('.layer').css('display', 'flex');
		html = "<img src='../../../static/images/change.png'><span class='msg_text'>" + text + "</span>"
		$('.layerMsg').html(html);

		setTimeout(_this.reset, 1500);
	},
	input: function(op) {
		var _this = this;
		_this.reset();
		var html = '',
		btns = '';
		$('.layer').addClass('input');
		$('.layer').css('display', 'flex');
		op.btnOp.btns.forEach((item, idx) => {
			btns += "<div class='btn'>" + item + "</div>"
		})
		html = '<div class="hd">' + op.title + '</div><div class="con"><input type="number" autofocus></div></div><div class="btns">' + btns + '</div>'
		$('.layerMsg').html(html)

		op.btnOp.handles.forEach((item, idx) => {
			$('.layer .btn').eq(idx).on('click', item)
		})
	},
	score: function(op) {
		var _this = this;
		_this.reset();
		var html = '',
		btns = '',
		liStr = '';
		$('.layer').addClass('score');
		$('.layer').css('display', 'flex');
		var i = 0;
		while(i < 5) {
			liStr += '<li class="star zymkwap ift-xing"></li>';
			i++
		}
		op.btnOp.btns.forEach((item, idx) => {
			btns += "<div class='btn'>" + item + "</div>"
		})
		html = '<div class="hd">' + op.title + '</div><div class="con"><div class="text">' + op.msg + '</div><ul class="starBox">' + liStr + '</ul></div><div class="btns">' + btns + '</div>'
		$('.layerMsg').html(html)

		op.btnOp.handles.forEach((item, idx) => {
			$('.layer .btn').eq(idx).on('click', item)
		})
		$('.layer .star').each((item_idx, item) => {
			$(item).on('click', function() {
				$(this).siblings().each((sb_idx, sb) => {
					if(item_idx > sb_idx) {
						$(item).addClass('active')
						$(sb).addClass('active')
					} else {
						$(sb).removeClass('active')
					}
				})
				score = (item_idx + 1) * 20
			})
		})
	},
	share: function(op) {
		var _this = this;
		_this.reset();
		var html = '';
		$('.layer').addClass('share');
		$('.layer').css('display', 'flex');
		html = '<div class="hd">' + op.title + '</div><div class="con"><div class="bdsharebuttonbox"><a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a></div></div>'
		$('.layerMsg').html(html)
		bd_share()
		$('.layer').on('click', _this.reset)
	},
	reset: function() {
		$('.layer').hide();
		$('.layer').off('click');
		$('.layer').attr('class', 'layer');
		$('.layerMsg').html('');
	}
}

function goback() {
	history.go(-1)
}

function isPurchase(chapter_id) {
	let isPurchase = this.purchaseData.some(item => {
		return item == chapter_id;
	})
	return isPurchase;
}

function collect() {
	if(isCollect) {

	// dom
	$('.like').removeClass('ift-lovered').addClass('ift-collect')

	// local storage
	let storData = getStore('subsList') || [];
	storData = storData.filter(item => {
		return item.comic_id != comic_id
	})
	setStore('subsList', storData)

	isCollect = !isCollect

	// server
	let action = 'del';
	if(userInfo) {
		$.ajax({
			url: api + 'setusercollect/',
			dataType: 'jsonp',
			data: { type, openid, action, comic_id },
			success: function(res) {
				if(res.status == 0) {
					layer.msg('取消收藏成功！')
					$('.sc .num').text(res.data.count);
				}
			},
			error: function (e) {
				layer.msg(e);
			}
		})
	} else {
		layer.msg('取消收藏成功！')
	}

} else {

	// dom
	$('.like').removeClass('ift-collect').addClass('ift-lovered')

	// local storage
	let tmpObj = {};
	tmpObj['comic_id'] = comic_id;
	tmpObj['comic_name'] = $('.info name').text();
	tmpObj['addtime'] = Date.now();

	let storData = getStore('subsList') || [];
	let isExist = storData.some(item => {
		return item.comic_id == tmpObj.comic_id
	})

	if(!isExist) {
		storData.push(tmpObj)
		setStore('subsList', storData)
	}

	isCollect = !isCollect

	// server
	let action = 'add';
	if(userInfo) {
		$.ajax({
			url: api + 'setusercollect/',
			dataType: 'jsonp',
			data: { type, openid, action, comic_id },
			success: function(res) {
				if(res.status == 0) {
					layer.msg('收藏成功！')
					$('.sc .num').text(res.data.count);
				}
			},
			error: function (e) {
				layer.msg(e);
			}
		})
	} else {
		layer.msg('收藏成功！')
	}
}
}

function add_gold() {
	let gold = $('.layer input').val();
	$.ajax({
		url: api + 'addgold/',
		dataType: 'jsonp',
		data: { type, openid, comic_id, gold },
		success: function(res) {
			if(res.status == 0) {
				layer.msg(`打赏成功，当前剩余${res.data.user_gold}金币`)
				$('.ds .num').text(res.data.comic_gold);
				// cookie
				userInfo.Cgold = res.data.user_gold;
				setCookie('user', JSON.stringify(userInfo));
			} else {
				layer.msg(res.msg)
			}
		},
		error: function (e) {
			layer.msg(e);
		}
	})
}

function add_score() {
	$.ajax({
		url: api + 'addscore/',
		dataType: 'jsonp',
		data: { type, openid, comic_id, score },
		success: function(res) {
			if(res.status == 0) {
				var score_span = (res.data.score / 10).toFixed(1)
				layer.msg('感谢您参与评价！')
				$('.df .num').text(res.data.jury);
				$('.info .score>span').text(score_span)
			} else {
				layer.msg(res.msg)
			}
		},
		error: function (e) {
			layer.msg(e);
		}
	})
}

function supTap(e) {
	let btn = e.target.dataset.btn;
	if(userInfo) {
		switch(btn) {
			case 'tj':
			$.ajax({
				url: api + 'addrecommend/',
				dataType: 'jsonp',
				data: { type, openid, comic_id },
				success: function(res) {
					if(res.status == 0) {
						layer.msg(`推荐成功，当前剩余${res.data.user_count}张推荐票`)
						$('.tj .num').text(res.data.count)
					} else {
						layer.msg(res.msg)
					}
				},
				error: function (e) {
					layer.msg(e);
				}
			})
			break;
			case 'ds':
			layer.input({
				title: '请输入您要打赏的金币数',
				btnOp: {
					btns: ['确定打赏', '取消'],
					handles: [add_gold, layer.reset]
				}
			})
			break;
			case 'yp':
			$.ajax({
				url: api + 'addmonthticket/',
				dataType: 'jsonp',
				data: { type, openid, comic_id },
				success: function(res) {
					if(res.status == 0) {
						layer.msg(`月票使用成功，当前剩余${res.data.user_ticket}张推荐票`);
						$('.yp .num').text(res.data.comic_ticket);
						// cookie
						userInfo.Cticket = res.data.user_count;
						setCookie('user', JSON.stringify(userInfo));
					} else {
						layer.msg(res.msg)
					}
				},
				error: function (e) {
					layer.msg(e);
				}
			})
			break;
			case 'df':
			layer.score({
				title: '打分',
				msg: '请给打分：',
				btnOp: {
					btns: ['确认', '取消'],
					handles: [add_score, layer.reset]
				}
			})
			break;
			case 'sc':
			collect()
			break;
			case 'fx':
			layer.share({ title: '分享' })
			break;
			default:
			break;
		}
	} else {
		switch(btn) {
			case 'sc':
			collect()
			break;
			case 'fx':
			layer.share({ title: '分享' })
			break;
			default:
			let login_from = location.href;
			let host = location.host;
			setCookie('login_from', login_from);
			location.href = '/login';
			// self.location = host + '/login'
			break;
		}
	}
}

function orderSwitch() {
	var reverse = $('.listItem').get().reverse();
	$('.listCon').html(reverse)
	if(orderBy) {
		$('.sortBtn').removeClass('ift-you1').addClass('ift-you')
		$('.sortBtn').text('逆序')
	} else {
		$('.sortBtn').removeClass('ift-you').addClass('ift-you1')
		$('.sortBtn').text('正序')
	}
	orderBy = !orderBy
}

$(function() {
 // 返回图标
 $('.goback').on('click', goback)
	// 收藏图标
	$('.like').on('click', collect)
	// 续看按钮
	if(readList.length > 0) {
		let read_info = readList.filter(item => {
			return item.comic_id == comic_id
		})
		if(read_info.length) {
			$('.read').eq(0).attr('href', '/read?comic_id=' + read_info[0].comic_id + '&chapter_id=' + read_info[0].chapter_id)
			$('.read').eq(0).text('续看：' + read_info[0].chapter_name);
			$('.read').eq(0).show();
			$('.read').eq(1).hide();
		}
	}
 // 章节顺序
 $('.sortBtn').on('click', orderSwitch)
	// 展开/收起章节
	$('.more').on('click', function() {
		if($('.listCon').hasClass('autoHeight')) {
			$('.listCon').removeClass('autoHeight')
			$(this).text('查看全部')
		} else {
			$('.listCon').addClass('autoHeight')
			$(this).text('收起')
		}
	})
	// 支持 按钮事件
	$('.sup-counts').on('click', supTap)
	// 榜单切换
	$('.rankBtn').on('click', function() {
		var rank = $(this).attr('data-rank');
		if(rank == 'hot') {
			$('.fansRank .hot').show()
			$('.fansRank .gold').hide()
		} else if(rank == 'gold') {
			$('.fansRank .hot').hide()
			$('.fansRank .gold').show()
		}
		$(this).attr('class', 'rankBtn active');
		$(this).siblings('.rankBtn').attr('class', 'rankBtn');
	})
})